package org.yuanqiframework.yuanqi.web.utils;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class WebUploadFileUtils {
    public static final String UPLOAD_PATH_DIR_NAME = "upload";
    public static final String UPLOAD_PATH_JAR_HOME;

    static {
        // 设置存放图片文件的路径
        String realPath = new ApplicationHome().getDir().getPath() + File.separator;
        File uploadDir = new File(realPath + UPLOAD_PATH_DIR_NAME);
        if (!uploadDir.exists()) {
            boolean mkdir = uploadDir.mkdir();
        }
        UPLOAD_PATH_JAR_HOME = realPath + UPLOAD_PATH_DIR_NAME + File.separator;
    }

    /**
     * http上传文件
     *
     * @param file
     * @param uploadPath
     * @return
     * @throws IOException
     */
    public static File upload(MultipartFile file, String uploadPath) throws IOException {
        if (file == null) {
            throw new RuntimeException("没有找到相对应的文件");
        }
        if (uploadPath == null || "".equals(uploadPath)) {
            uploadPath = UPLOAD_PATH_JAR_HOME;
        } else {
            File f = new File(uploadPath);
            if (!f.exists()) {
                f.mkdir();
            }
            uploadPath = f.getPath() + File.separator;
        }
        String path = null;// 文件路径
        String fileName = file.getOriginalFilename();// 文件原名
        assert fileName != null;
        path = uploadPath + UUID.randomUUID().toString().replace("-", "") + "." + FileUtils.getFileSuffix(fileName);
        // 转存文件到指定的路径
        File newFile = new File(path);
        file.transferTo(newFile);
        return newFile;
    }

    public static File upload(MultipartFile file) throws IOException {
        return upload(file, null);
    }

}
